<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="1200px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="120px" :disabled="viewMode">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="来源单号" prop="sourceNo">
              <el-input v-model="formData.sourceNo" placeholder="请输入来源单号" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检来源类型" prop="sourceType">
              <el-select v-model="formData.sourceType" placeholder="请选择质检来源类型" filterable clearable style="width: 100%">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.QUALITY_SOURCE_TYPE)" :key="dict.value" :label="dict.label"
                           :value="parseInt(dict.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检方案" prop="inspectionSchemeId">
              <el-select v-model="formData.inspectionSchemeId" placeholder="请选择质检方案" filterable clearable
                         :remote="true" :remote-method="remoteMethodInspectionScheme"
                         :loading="loadingInspectionScheme" style="width: 100%">
                <el-option v-for="item in inspectionSchemeList" :key="item.id" :label="item.schemeName + '(' + item.schemeCode + ')'"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检方式" prop="schemeMethod">
              <el-select v-model="formData.schemeMethod" placeholder="请选择质检方式" filterable style="width: 100%">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SCHEME_METHOD)" :key="dict.value" :label="dict.label"
                           :value="parseInt(dict.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 根据质检方式动态显示抽检比例或抽检数量 -->
            <el-form-item
              :label="formData.schemeMethod === 2 ? '抽检比例' : (formData.schemeMethod === 3 ? '抽检数量' : '')"
              prop="samplingRatio"
              v-if="formData.schemeMethod === 2 || formData.schemeMethod === 3">
              <el-input
                v-model="formData.samplingRatio"
                :placeholder="formData.schemeMethod === 2 ? '请输入抽检比例' : '请输入抽检数量'"
                style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检类型" prop="schemeType">
              <el-select v-model="formData.schemeType" placeholder="请选择质检类型" filterable style="width: 100%">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SCHEME_TYPE)" :key="dict.value" :label="dict.label"
                           :value="parseInt(dict.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料" prop="materialId">
              <el-select v-model="formData.materialId" placeholder="请选择物料" filterable clearable
                         :remote="true" :remote-method="remoteMethodMaterial"
                         :loading="loadingMaterial" style="width: 100%" @change="handleMaterialChange">
                <el-option v-for="item in materialList" :key="item.id" :label="item.materialName"
                           :value="item.id">
                  <span style="float: left">{{ item.materialName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.materialNo }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="工序" prop="processId">-->
<!--              <el-select v-model="formData.processId" placeholder="请选择工序" filterable clearable-->
<!--                         :remote="true" :remote-method="remoteMethodProcedure"-->
<!--                         :loading="loadingProcedure" style="width: 100%" @change="handleProcedureChange">-->
<!--                <el-option v-for="item in procedureList" :key="item.id" :label="item.procedureName + '(' + item.procedureCode + ')'"-->
<!--                           :value="item.id"/>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="巡检间隔(min)" prop="intervalTime">
              <el-input clearable v-model="formData.intervalTime"
                       placeholder="请输入巡检间隔(min)" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检原因" prop="qualityReason">
              <el-select v-model="formData.qualityReason" placeholder="请选择质检原因" filterable style="width: 100%">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.QUALITY_REASON)" :key="dict.value" :label="dict.label"
                           :value="parseInt(dict.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchNo">
              <el-input v-model="formData.batchNo" placeholder="请输入批次号" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检总数" prop="totalQuantity">
              <el-input v-model.number="formData.totalQuantity" type="number" placeholder="请输入质检总数" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)"
                          :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!viewMode" type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as InspectionSchemeTaskApi from '@/api/quality/inspectionschemetask';
import * as InspectionSchemeApi from '@/api/quality/inspectionscheme';
import * as MaterialApi from '@/api/basic/material';
import * as ProcedureApi from '@/api/basic/procedure';
import { getDictDatas, getDictDataLabel, DICT_TYPE } from '@/utils/dict';

export default {
  name: "InspectionSchemeTaskForm",
  components: {},
  props: {
    // 是否为查看模式
    viewMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 加载状态
      loadingInspectionScheme: false,
      loadingMaterial: false,
      loadingProcedure: false,
      // 下拉列表数据
      inspectionSchemeList: [],
      materialList: [],
      procedureList: [],
      // 表单参数
      formData: {
        id: undefined,
        sourceNo: undefined,
        sourceType: undefined,
        inspectionSchemeId: undefined,
        materialId: undefined,
        materialNo: undefined,
        materialName: undefined,
        processId: undefined,
        procedureCode: undefined,
        procedureName: undefined,
        schemeMethod: undefined,
        schemeType: undefined,
        intervalTime: undefined,
        samplingRatio: undefined,
        qualityReason: undefined,
        batchNo: undefined,
        totalQuantity: undefined,
        remark: undefined,
        status: '1' // 状态默认开启
      },
      // 表单校验
      formRules: {
        sourceNo: [{required: true, message: '来源单号不能为空', trigger: 'blur'}],
        sourceType: [{required: true, message: '质检来源类型不能为空', trigger: 'change'}],
        inspectionSchemeId: [{required: true, message: '质检方案不能为空', trigger: 'change'}],
        materialId: [{required: true, message: '物料不能为空', trigger: 'change'}],
        processId: [{required: true, message: '工序不能为空', trigger: 'change'}],
        schemeMethod: [{required: true, message: '质检方式:1-全检2-比例3-固定4-自定义不能为空', trigger: 'blur'}],
        schemeType: [{required: true, message: '质检类型:1-首件检2-末件3-生产4-巡检5-入库6-出库7-来料不能为空', trigger: 'change'}],
        totalQuantity: [{required: true, message: '质检总数不能为空', trigger: 'blur'}, {type: 'number', message: '请输入有效的数字', trigger: 'blur'}],
      },
    };
  },
  created() {
    // 进入页面时获取初始数据
    this.getInspectionSchemes();
    this.getMaterials();
    this.getProcedures();
  },
  methods: {
    /** 打开弹窗 */
    async open(id, viewMode) {
      // 更新查看模式
      this.viewMode = viewMode; // 直接设置组件内部的viewMode值
      this.$emit('update:viewMode', viewMode);
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await InspectionSchemeTaskApi.getInspectionSchemeTask(id);
          this.formData = res.data;
          this.dialogTitle = viewMode ? "查看质检任务" : "修改质检任务";

          // 为远程搜索字段调用remote-method，确保显示名称
          // 1. 质检方案搜索
          if (this.formData.inspectionSchemeId) {
            // 尝试根据ID获取详细信息，或者使用名称进行搜索
            await this.remoteMethodInspectionScheme('');
          }

          // 2. 物料搜索
          if (this.formData.materialId) {
            await this.remoteMethodMaterial('');
            // 确保materialNo和materialName正确设置
            if (!this.formData.materialNo || !this.formData.materialName) {
              await this.remoteMethodMaterial(this.formData.materialName || this.formData.materialNo);
            }
          }

          // 3. 工序搜索
          if (this.formData.processId) {
            await this.remoteMethodProcedure('');
            // 确保procedureCode和procedureName正确设置
            if (!this.formData.procedureCode || !this.formData.procedureName) {
              await this.remoteMethodProcedure(this.formData.procedureName || this.formData.procedureCode);
            }
          }
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增质检任务";
      }
    },

    /** 获取质检方案列表 */
    async getInspectionSchemes() {
      try {
        const res = await InspectionSchemeApi.getInspectionSchemePage({ pageSize: 100 });
        this.inspectionSchemeList = res.data.list || [];
      } catch (error) {
        this.$message.error('获取质检方案列表失败');
      }
    },

    /** 远程搜索质检方案 */
    async remoteMethodInspectionScheme(query) {
      if (!query) {
        this.getInspectionSchemes();
        return;
      }
      this.loadingInspectionScheme = true;
      try {
        const res = await InspectionSchemeApi.getInspectionSchemePage({
          pageSize: 100,
          schemeName: query,
          schemeCode: query
        });
        this.inspectionSchemeList = res.data.list || [];
      } catch (error) {
        this.$message.error('搜索质检方案失败');
      } finally {
        this.loadingInspectionScheme = false;
      }
    },

    /** 获取物料列表 */
    async getMaterials() {
      try {
        const res = await MaterialApi.getMaterialPage({ pageSize: 100 });
        this.materialList = res.data.list || [];
      } catch (error) {
        this.$message.error('获取物料列表失败');
      }
    },

    /** 远程搜索物料 */
    async remoteMethodMaterial(query) {
      if (!query) {
        await this.getMaterials();
        return;
      }
      this.loadingMaterial = true;
      try {
        const res = await MaterialApi.getMaterialPage({
          pageSize: 100,
          materialName: query,
          materialNo: query
        });
        this.materialList = res.data.list || [];
      } catch (error) {
        this.$message.error('搜索物料失败');
      } finally {
        this.loadingMaterial = false;
      }
    },

    /** 处理物料选择变化 */
    handleMaterialChange(value) {
      const material = this.materialList.find(item => item.id === value);
      if (material) {
        this.formData.materialNo = material.materialNo;
        this.formData.materialName = material.materialName;
      } else {
        this.formData.materialNo = undefined;
        this.formData.materialName = undefined;
      }
    },

    /** 获取工序列表 */
    async getProcedures() {
      try {
        const res = await ProcedureApi.getProcedurePage({ pageSize: 100 });
        this.procedureList = res.data.list || [];
      } catch (error) {
        this.$message.error('获取工序列表失败');
      }
    },

    /** 远程搜索工序 */
    async remoteMethodProcedure(query) {
      if (!query) {
        this.getProcedures();
        return;
      }
      this.loadingProcedure = true;
      try {
        const res = await ProcedureApi.getProcedurePage({
          pageSize: 100,
          procedureName: query,
          procedureCode: query
        });
        this.procedureList = res.data.list || [];
      } catch (error) {
        this.$message.error('搜索工序失败');
      } finally {
        this.loadingProcedure = false;
      }
    },

    /** 处理工序选择变化 */
    handleProcedureChange(value) {
      const procedure = this.procedureList.find(item => item.id === value);
      if (procedure) {
        this.formData.procedureCode = procedure.procedureCode;
        this.formData.procedureName = procedure.procedureName;
      } else {
        this.formData.procedureCode = undefined;
        this.formData.procedureName = undefined;
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await InspectionSchemeTaskApi.updateInspectionSchemeTask(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await InspectionSchemeTaskApi.createInspectionSchemeTask(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        sourceNo: undefined,
        sourceType: undefined,
        inspectionSchemeId: undefined,
        materialId: undefined,
        materialNo: undefined,
        materialName: undefined,
        processId: undefined,
        procedureCode: undefined,
        procedureName: undefined,
        schemeMethod: undefined,
        schemeType: undefined,
        intervalTime: undefined,
        samplingRatio: undefined,
        qualityReason: undefined,
        batchNo: undefined,
        totalQuantity: undefined,
        remark: undefined,
        status: 1 // 状态默认开启
      };
      this.resetForm("formRef");
    }
  }
};
</script>

<style scoped lang="scss">
:deep(.el-input__inner:disabled),
:deep(.el-select__inner:disabled),
:deep(.el-date-editor .el-input__inner:disabled),
:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #F9F9F9 !important;
  color: #333 !important;
  border-color: #DCDFE6 !important;
}

:deep(.vue-treeselect--disabled) {
  background-color: #F9F9F9 !important;
  .vue-treeselect__control {
    background-color: #F9F9F9 !important;
    color: #333 !important;
  }
}
</style>
